<template>
  <div class="my">
    <!-- 我的页面 -->
    <header>
      <div class="top" :style="{ backgroundImage: `url(${bgImage})` }">
        <!-- 未登录的状态 -->
        <div class="headimg" v-if="!loginStatus">
          <img src="../../assets/my/nologin1.webp" alt="" />
        </div>
        <div class="nickname nologinname" v-if="!loginStatus" @click="goLogin">
          点击登录/注册
        </div>
        <!-- 登录后展示用户信息 -->
        <div class="headimg" v-if="loginStatus" @click="changeHead">
          <!-- <img src="../../assets/my/head1.webp" alt="" /> -->
          <img :src="userInfo.data[0].user_photo" alt="" />
        </div>
        <div class="nickname" v-if="loginStatus">
          {{ userInfo.data[0].user_name }}
        </div>
      </div>
      <div class="bottom">
        <div class="item" @click="personAttestation(loginStatus)">
          校园认证
          <!-- <span class="item-islogin" v-if="loginStatus">
            <van-tag type="warning" v-if="obj[0].student_attesation == 0"
              >未认证</van-tag
            >
            <van-tag type="success" v-else>认证成功</van-tag>
          </span> -->
        </div>
        <div class="item" @click="myshop(loginStatus)">我的店铺</div>
        <div class="item">交易记录</div>
      </div>
    </header>
    <div class="getshop">
      <div class="one" @click="goPay">
        <van-icon
          name="balance-pay"
          size="30px"
          :badge="toBeShippedNum"
        />待付款
      </div>
      <div class="one" @click="toBeShipped">
        <van-icon
          name="logistics"
          size="30px"
          :badge="toBeShippedPayNum"
        />待发货
      </div>
      <div class="one">
        <van-icon name="comment-o" @click="gofeedback" size="30px" />反馈/意见
      </div>
    </div>
    <section>
      <div class="list">
        <div class="list1">
          <ul>
            <li @click="goMyInformation" v-if="loginStatus">
              <span>个人资料</span>
            </li>
            <li @click="goMyShippingAddress" v-if="loginStatus">
              <span>收货地址</span>
            </li>
            <li @click="changeBackgroundImage"><span>主题切换</span></li>
            <li @click="test" v-if="loginStatus"><span>人脸录入</span></li>
            <li @click="returnLoginOut" v-if="loginStatus">
              <span>退出登录</span>
            </li>
          </ul>
        </div>
      </div>
    </section>

    <van-popup
      v-model="show"
      round
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-uploader :after-read="afterRead">
        <div class="items">头像</div>
      </van-uploader>
      <div class="items" @click="goUserInfo">个人资料</div>
      <div class="items" @click="cancelPop">取消</div>
    </van-popup>

    <Tabber></Tabber>
  </div>
</template>

<script>
// import Wave from "@/components/specialeffect/Wave"
import { mapMutations, mapState } from "vuex"
import Tabber from "@/components/common/Tabber"
import { Toast } from "vant"
import OSS from "ali-oss"
export default {
  name: "my",
  components: {
    Tabber,
  },
  data() {
    return {
      obj: [],
      show: false,
      imageUrl: "",
      toBeShippedNum: "",
      toBeShippedPayNum: "",
      bgImage: require("../../assets/my/gra.webp"), // 设置默认背景图片路径
    }
  },

  created() {
    console.log("执行了")
    this.userInit()
    // console.log(this.userInit())
    this.isSuccessCheck()
    // 查询订单数目
    this.getOrderNum()
  },

  methods: {
    // 人脸录入
    test() {
      // 暂时不获取token
      // this.$api.my.userFace().then((res) => {
      //   console.log(JSON.parse(res.data))
      // })

      this.$router.push("/takephoto")
    },

    // 获取订单数量
    getOrderNum() {
      this.$api.my.getOrderNum().then((res) => {
        // this.toBeShippedNum = res.data.length
        // console.log(this.toBeShippedNum)
        let datas = JSON.parse(JSON.stringify(res.data))
        console.log(datas)
        let { r, resluts } = datas
        console.log(r)
        console.log(resluts)
        this.toBeShippedNum = resluts.length
        this.toBeShippedPayNum = r.length
      })
    },

    cancelPop() {
      this.show = false
    },

    usertext() {
      this.$api.index.indexTest().then((res) => {
        console.log(res)
      })
    },

    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file)
      let files = file
      let self = this
      let client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: "oss-cn-chengdu",
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        accessKeyId: "LTAI5tHCZfeVG9u9148M1csc",
        accessKeySecret: "vLPa7tCkDqAULsBpymLzqrdNAaCmFO",
        bucket: "liulin",
        secure: true, //开启https
      })
      async function uploadImage() {
        try {
          let name = files.file.name
          let index = name.lastIndexOf(".")
          let ext = name.substr(index + 1)
          const result = await client.put(
            "shopimgs/" + new Date().getTime() + "." + ext,
            files.file
          )
          //返回的图片路径
          self.imageUrl = result.url
          console.log(1)
          console.log(self.imageUrl)
          if (self.imageUrl.length > 0) {
            //上传到服务器
            // const params = {
            //   content: self.textarea,
            //   imgs: JSON.stringify(self.image_urls),
            //   location: self.userlocal,
            // }
            self.$emit("getData", self.imageUrl)
            // 将imgUrl保存数据库里面
            let params = { imgUrl: self.imageUrl }
            await self.$api.my.headImgData(params).then((res) => {
              console.log(res)
              // 更新前端localstoreage中的数据
              let User = JSON.parse(localStorage.getItem("UserShopInfo"))
              let newValue = {
                user_photo: res.data[0].user_photo,
              }
              Object.assign(User.data[0], newValue)
              localStorage.setItem("UserShopInfo", JSON.stringify(User))
            })
            self.show = false
            self.userInit()
            // self.$router.push("/my")
          }
        } catch (e) {
          console.log(e)
          Toast("头像上传失败！")
        }
      }
      // 调用上传
      uploadImage()
    },

    gofeedback() {
      this.$router.push("/feedback")
    },

    // 收购地址
    goMyShippingAddress() {
      this.$router.push("/shopaddress")
    },
    goUserInfo() {
      this.goMyInformation()
    },

    // changeHead() {
    //   this.$router.push("/upload")
    // },
    // 点击展示头像和个人资料
    changeHead() {
      // this.$router.push("/upload")
      this.show = true
    },

    toBeShipped() {
      if (!this.loginStatus) {
        Toast("请先登录账号")
      } else {
        this.$router.push("/tobeshipped")
      }
    },

    // 进入待付款界面
    goPay() {
      if (!this.loginStatus) {
        Toast("请先登录账号")
      } else {
        this.$router.push("/order")
      }
    },

    changeBackgroundImage() {
      let options = [
        "https://liulin.oss-cn-chengdu.aliyuncs.com/background/IMG_7934.JPG",
        "https://liulin.oss-cn-chengdu.aliyuncs.com/background/IMG_7909.JPG",
      ]
      // 上一个随机值和索引
      let lastRandomIndex = -1
      let lastRandomValue = ""

      // 随机选择下一个元素
      function selectRandomOption() {
        let randomIndex = lastRandomIndex
        while (randomIndex === lastRandomIndex) {
          randomIndex = Math.floor(Math.random() * options.length)
        }
        lastRandomIndex = randomIndex
        lastRandomValue = options[randomIndex]
        return lastRandomValue
      }

      // 第一次随机选择图片
      let firstChoice = selectRandomOption()

      console.log(firstChoice)
      while (firstChoice == this.bgImage) {
        firstChoice = selectRandomOption()
      }
      this.bgImage = firstChoice
    },

    // 校园认证
    personAttestation(loginStatus) {
      if (!loginStatus) {
        Toast("请先登录账号")
      } else {
        this.$router.push("/attestation")
      }
    },

    // 判断是否认证成功
    isSuccessCheck() {
      if (!this.loginStatus) return
      this.$api.my.userIsCheck().then((res) => {
        this.obj = res.data
      })
    },

    // 跳转到我的店铺
    myshop(loginStatus) {
      if (!loginStatus) {
        Toast("请先登录账号")
      } else {
        this.$router.push("/myshop")
      }
    },

    // 跳转到登录页面
    goLogin() {
      this.$router.push("/login")
    },
    // 跳转到我的资料页面
    goMyInformation() {
      let userInfo = JSON.parse(localStorage.getItem("UserShopInfo")).data[0]
      delete userInfo.user_address
      delete userInfo.user_photo
      delete userInfo.user_state
      this.$router.push({
        path: "/myinformation",
        query: {
          userInfo,
        },
      })
    },
    returnLoginOut() {
      this.loginOut()
      this.$router.push("/login")
    },
    // 退出登录
    ...mapMutations(["loginOut", "userInit"]),
  },

  computed: {
    ...mapState({
      loginStatus: (state) => state.user.loginStatus,
      userInfo: (state) => state.user.userInfo,
    }),
  },
}
</script>

<style lang="less" scoped>
.my {
  position: relative;
  width: 100vw;
  height: 100vh;
  // background-color: pink;
}

header {
  position: relative;
  width: 100%;
  height: 18.75rem /* 300/16 */ /* 280/16 */;
  // box-shadow: 0px 5px 0px 0px rgb(7, 7, 7, 0.5);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  // border-bottom: 1px solid black;
  .top {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 13.75rem /* 220/16 */;
    // background-color: green;

    // 自己写的
    // background-image: url("../assets/my/gra1.webp");
    // background-repeat: no-repeat;
    // background-attachment: fixed;
    // background-position: center center;
    // background-size: 100%;
    // 以下是标准写法
    background-size: cover; /* 图片自适应尺寸填充元素 */
    background-position: center center; /* 将图片放置在元素中心 */
    background-repeat: no-repeat; /* 禁止重复显示图片 */
    width: 100%;
    overflow: hidden;
    background-size: cover; //或者background-size:100%;

    .headimg {
      // overflow: hidden;
      width: 5rem /* 80/16 */ /* 100/16 */ /* 50/16 */;
      height: 5rem /* 80/16 */ /* 100/16 */ /* 50/16 */;
      // border-radius: 50%;
      // background-color: red;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
      }
    }

    .nickname {
      color: #fff;
      // text-shadow: 1px 1px 2px pink;
      margin-top: 0.3125rem /* 5/16 */;
      font-size: 1.125rem /* 18/16 */;
    }

    .nologinname {
      color: rgb(172, 21, 109);
    }
  }
  .bottom {
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-wrap: wrap;

    width: 100%;
    height: 5rem /* 80/16 */;
    // background-color: pink;
  }
}

.items {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 60px;
  border-bottom: 1px solid rgb(222, 225, 230);
}

.getshop {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 87%;
  margin: 2.5rem /* 40/16 */ auto;
  margin-top: 1.875rem /* 30/16 */ /* 40/16 */;
  margin-bottom: 0px;
  height: 2.5rem /* 40/16 */;
  background-color: #fff;
  // box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  .one {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

section {
  margin-top: 1.5625rem /* 25/16 */ /* 30/16 */;
  z-index: inherit;
  padding: 0 1.25rem 1.25rem 1.25rem /* 20/16 */;
  // background-color: rgb(251, 249, 249);
  background-color: #fff;
  .list1 {
    margin-top: 0.625rem /* 10/16 */;
    width: 100%;
    // height: 100px;
    // box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
    box-shadow: 0 0 10px 8px rgb(0 0 0 / 10%);
    // border-radius: 1.25rem /* 20/16 */ /* 15/16 */;
    ul {
      background-color: #fff;
    }

    ul li {
      width: 100%;
      height: 2.5rem /* 40/16 */;
      line-height: 2.5rem /* 40/16 */;
      border-bottom: 1px solid rgb(240, 238, 238);

      span {
        padding: 0 0 0 0.625rem /* 10/16 */;
      }
    }
  }
}
</style>
